package com.kuaigou.cim.mq;

import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.farsunset.cim.nio.mutual.Message;
import com.farsunset.ichat.cim.push.DefaultMessagePusher;
import com.farsunset.ichat.cim.push.SystemMessagePusher;
import com.farsunset.ichat.common.util.Constants;
import com.farsunset.ichat.common.util.ContextHolder;
import com.kuaigou.cim.util.JSONHelper;
import com.kuaigou.cim.util.StringUtil;

public class CimMessageConsumer extends ObjectMessageConsumer {
	
	private Logger logger = LoggerFactory.getLogger(getClass());	

	@Override
	public void processMessage(Object message) {
		System.out.println("222222222222:"  + message);
		Message msg = (Message)message;
		try {
			msg.setMapStr(JSONHelper.objectToJson(msg.getData(), HashMap.class));
		} catch (Exception e1) {
			e1.printStackTrace();
		}	
		if(StringUtil.isEmpty(msg.getSender())){
			msg.setSender(Constants.KG_SYSTEM);
		}
		try{	        
			checkParams(msg);	        
			if(Constants.KG_SYSTEM.equals(msg.getSender())){
				logger.info("SystemMessagePusher" + msg.toString());
				  //向客户端 发送消息
		        ContextHolder.getBean(SystemMessagePusher.class).pushMessageToUser(msg);
			}else{
				logger.info("DefaultMessagePusher" + message.toString());
				  //向客户端 发送消息
		        ContextHolder.getBean(DefaultMessagePusher.class).pushMessageToUser(msg);
			}	             
	       
		}catch(Exception e){				
			logger.error("推送消息失败：" + e.getMessage() + "." + msg.toString());
		}
   
		
	}
	
    private void checkParams(Message msg) throws Exception    {    	   
          if(StringUtil.isEmpty(msg.getReceiver())) {
        	  throw new RuntimeException("receiver 不能为空!");        	  
          }
//          String account = msg.getReceiver();
//          String verificationCode = msg.getVerificationCode();	    
//          if(verificationCode == null || account == null ||  !account.equals(AESEncodeUtil.decrypt(verificationCode,AESEncodeUtil.key))){
//        	  throw new RuntimeException("校验码不正确!");        
//          }			
          
    }
	

}
